<template>
  <el-row>
    <el-col :span="5" style="padding-left: 10px; padding-top: 20px; border-right: 1px solid #dfe6ec; display: block">
      <customTree :ancestralId="listQuery.ancestralId" :btnTitle="'  新建目录  '" @getId="getId" :type="false" @getTree="getTree" :expandType="'1'" />
    </el-col>
    <el-col :span="18">
      <div class="app-container">
        <div class="filter-container">
          <div class="filter-item">
            <span class="span">API名称 </span>
            <el-input v-model="listQuery.apiName" placeholder="请输入API名称" style="width: 200px" />
          </div>
          <div class="filter-item">
            <span class="span">API路径 </span>
            <el-input v-model="listQuery.apiUrl" placeholder="请输入API路径" style="width: 200px" />
          </div>
          <div class="filter-item">
            <span class="span">请求方式 </span>
            <el-select v-model="listQuery.reqMethod" clearable placeholder="请选择请求方式" style="width: 200px">
              <el-option v-for="item in dictList('req_type')" :key="'type' + item.label" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="filter-item">
            <span class="span">状态 </span>
            <el-select v-model="listQuery.status" clearable placeholder="请选择状态" style="width: 200px">
              <el-option v-for="item in statusOptions" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>
          </div>

          <!-- <div class="filter-item">
            <span class="span">是否申请 </span>
            <el-select v-model="listQuery.examineStatus" clearable placeholder="是否申请" style="width: 200px;">
              <el-option v-for="item in examineStatus" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>
          </div> -->

          <!--      <div class="filter-item">-->
          <!--        <span>状态:</span>-->
          <!--        <el-radio-->
          <!--          v-for="item in dictList('is_release')"-->
          <!--          :key="'type' + item.label"-->
          <!--          v-model="listQuery.status"-->
          <!--          :label="item.value">-->
          <!--          {{ item.label }}-->
          <!--        </el-radio>-->
          <!--      </div>-->
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
            {{ $t('table.search') }}
          </el-button>
          <el-button plain v-waves v-permission="['MarketApi:MarketApi:add']" class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-edit" @click="handleCreate">
            {{ $t('table.add') }}
          </el-button>
          <el-button plain v-waves v-permission="['MarketApi:MarketApi:delete']" class="filter-item" style="margin-left: 10px" type="danger" icon="el-icon-delete" @click="handleBathDelete">
            {{ $t('table.delete') }}
          </el-button>
          <!--      <el-button v-waves v-permission="['MarketApi:MarketApi:import']" class="filter-item" type="primary" icon="el-icon-upload2" @click="handleImport">-->
          <!--        {{ $t('table.import') }}-->
          <!--      </el-button>-->
          <el-button v-waves v-permission="['MarketApi:MarketApi:export']" :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleExport">
            {{ $t('table.export') }}
          </el-button>
          <el-button v-waves class="filter-item" icon="el-icon-refresh" @click="handleRest">{{ $t('table.rest') }}</el-button>
        </div>

        <el-table ref="table" :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" align="center" type="index" width="50" fixed="left" />
          <el-table-column label="API名称" align="center" min-width="300px" fixed="left">
            <template slot-scope="{ row }">
              <span>{{ row.apiName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="API版本" align="center" min-width="80px">
            <template slot-scope="{ row }">
              <span>{{ row.apiVersion }}</span>
            </template>
          </el-table-column>
          <el-table-column label="API路径" align="center" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.apiUrl }}</span>
            </template>
          </el-table-column>
          <el-table-column label="请求方式" align="center" min-width="110px">
            <template slot-scope="{ row }">
              <span>{{ row.reqMethod | dictLabel('req_type') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="返回格式" min-width="110px" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.resType | dictLabel('res_type') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="110px" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.status | dictLabel('is_release') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数据源" align="center" min-width="150px">
            <template slot-scope="{ row }">
              <span v-if="row.sourceName">{{ row.sourceName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="330" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="{ row }">
              <el-button v-permission="['MarketApi:MarketApi:use']" type="text" size="small" icon="el-icon-document-copy" @click="handleUse(row)" v-if="row.examineStatus == 1"> 申请使用 </el-button>
              <el-button v-permission="['MarketApi:MarketApi:update']" type="text" size="small" icon="el-icon-edit" @click="handleUpdate(row)">
                {{ $t('table.edit') }}
              </el-button>
              <el-button v-permission="['MarketApi:MarketApi:info']" type="text" size="small" icon="el-icon-tickets" @click="handleInfo(row)"> 详情 </el-button>
              <el-button v-if="row.status === '1' || row.status === '3'" v-permission="['MarketApi:MarketApi:push']" type="text" size="small" icon="el-icon-edit" @click="handlePush(row)">
                发布
              </el-button>
              <el-button v-if="row.status === '2'" v-permission="['MarketApi:MarketApi:cancel']" type="text" size="small" icon="el-icon-bottom" @click="handleCancel(row)"> 下线 </el-button>
              <el-button v-permission="['MarketApi:MarketApi:delete']" type="text" size="small" icon="el-icon-delete" class="delete-text-btn" @click="handleDelete(row, 'deleted')">
                {{ $t('table.delete') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <import ref="import" template-url="/MarketApi/MarketApi/template" import-url="/MarketApi/MarketApi/import" @refreshList="getList" />
        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" :page-sizes="pageArray" @pagination="getList" />

        <market-api-form ref="form" @refreshList="getList" />
        <market-api-info ref="info" @refreshList="getList" />
      </div>
    </el-col>
  </el-row>
</template>

<script>
import { deleteMarketApi, fetchMarketApiList, exportMarketApi, pushMarketApi, cancelMarketApi, getUse } from '@/api/marketApi/marketApi'
import Import from '@/components/Import/import'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission/permission'
import marketApiForm from './marketApiForm'
import marketApiInfo from './marketApiInfo'
import Pagination from '@/components/Pagination'
import { fetchsourceList } from '@/api/metadata/source'
import customTree from '@/components/customTree/index.vue'
export default {
  name: 'MarketApiList',
  components: { marketApiForm, marketApiInfo, Pagination, Import, customTree },
  directives: { waves, permission },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      multipleSelection: [],
      downloadLoading: false,
      listLoading: true,
      pageArray: this.$store.getters.pageArray,
      listQuery: {
        apiName: undefined,
        reqMethod: undefined,
        status: undefined,
        examineStatus: undefined,

        apiUrl: undefined,
        page: 1,
        ancestralId: '6',
        limit: this.$store.getters.defaultPageSize,
      },
      treeList: [],
      labelList: [],
      currentNodekey: '',
      treeData: [],
      defaultProps: {
        // 默认设置
        children: 'children',
        label: 'name',
      },
      NODE_KEY: 'id',
      filterText: '',
      statusOptions: [
        { id: 2, label: '已发布' },
        { id: 3, label: '已下线' },
      ],
      examineStatus: [
        { id: 0, label: '已申请' },
        { id: 1, label: '未申请' },
      ],
    }
  },
  computed: {
    ids() {
      const ids = []
      this.multipleSelection.forEach((ele) => {
        ids.push(ele.id)
      })
      return ids.join(',')
    },
  },

  watch: {
    filterText(val) {
      this.$refs.SlotTree.filter(val)
    },
  },
  methods: {
    getId(data) {
      this.listQuery.ancestralId = '6'
      this.listQuery.directoryId = data.id
      this.getList()
    },
    getTree(data) {
      this.treeList = data
    },

    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleNodeClick(val) {
      if (val.parentId === '0') {
        this.listQuery.directoryId = null
        this.getListAll()
      } else {
        this.listQuery.directoryId = val.id
        this.getList()
      }
    },
    getList() {
      this.listLoading = true
      fetchMarketApiList(this.listQuery).then((response) => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getListAll() {
      this.listLoading = true
      const dId = this.listQuery.directoryId
      this.listQuery.directoryId = undefined
      fetchMarketApiList(this.listQuery).then((response) => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
      this.listQuery.directoryId = dId
    },

    handleCreate() {
      if (this.listQuery.directoryId) {
        this.$refs.form.handleCreate(this.listQuery.directoryId)
      } else {
        this.$message.warning('请选择目录')
      }
    },
    handleUpdate(row) {
      this.$refs.form.handleUpdate(row.id)
    },
    handleInfo(row) {
      this.$refs.info.handleInfo(row.id)
    },
    handlePush(row) {
      pushMarketApi(row.id).then((response) => {
        if (response.data.code === 0) {
          this.getList()
          this.$message.success(response.data.msg)
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    handleCancel(row) {
      cancelMarketApi(row.id).then((response) => {
        if (response.data.code === 0) {
          this.getList()
          this.$message.success(response.data.msg)
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    handleDelete(row) {
      if (row.status === '2') {
        this.$message.error('接口已发布，请先下线接口再删除')
        return handleDelete
      }
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteMarketApi(row.id).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleUse(row) {
      this.$confirm('确定申请使用吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        getUse({ apiId: row.id }).then((res) => {
          if (res.data.code == 0) {
            this.$message.success(res.data.msg)
            this.getList()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleBathDelete() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.multipleSelection.forEach((ele) => {
        if (ele.status === '2') {
          this.$message.error('接口已发布，请先下线接口再删除')
          return handleBathDelete
        }
      })
      this.$confirm('确定删除所选数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteMarketApi(this.ids).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleImport() {
      this.$refs.import.show()
    },
    handleExport() {
      this.downloadLoading = true
      exportMarketApi(this.ids).then((response) => {
        this.downloadLoading = true
        if (response.data.code === 0) {
          import('@/vendor/Export2Excel').then((excel) => {
            excel.export_byte_to_excel(response.data.data.bytes, response.data.data.title)
            this.downloadLoading = false
          })
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    //重置
    handleRest() {
      this.listQuery = {
        directoryId: this.listQuery.directoryId,
        page: this.listQuery.page,
        limit: this.$store.getters.defaultPageSize,
      }
      this.getList()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep(::-webkit-scrollbar) {
  display: block !important;
}

.table-expand {
  font-size: 0;
}

.table-expand label {
  width: 90px;
  color: #99a9bf;
}

.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.row {
  display: flex;
}

.el-row {
  display: flex;
}

.el-col-5 {
  flex: 1;
}

.span {
  color: #606266;
  font-weight: 700;
  font-size: 14px;
}
</style>
